package com.ch.base.element;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;

import com.ch.base.factory.ActionFactory;
import com.ch.base.factory.SysUseLogInfoFactory;
import com.ch.base.obj.LoginObj;
import com.ch.base.util.EhcacheUtil;
import com.ch.base.util.OtherUtils;
import com.opensymphony.xwork2.Preparable;

public abstract class BaseAction<T>  extends ActionFactory implements Preparable, SessionAware {
	protected Map session;
	protected T actionForm;						

	protected LoginObj loginObj;			//登入者資訊
	protected String errorMsg = "";			//錯誤訊息
	protected String errorSolution = "";	//錯誤解決方式
	
	protected List displayList; 			//欲顯示的列表
	protected int pageSize = 10;			//欲顯示的列表每頁筆數
	protected int totalPage = 1;			//顯示的列表總頁數
	protected int totalSize = 0;			//欲顯示的列表總筆數
	protected int currentPage = 1;			//顯示的列表當前頁數
//	protected int prevPage = 1;				//顯示的列表上一頁數
	protected int nextPage = 1;				//顯示的列表下一頁數
	
	public void validate() {
		try {
			SysUseLogInfoFactory.setLogInformation();
			loginObj = this.getSession("loginObj") != null ?  (LoginObj)this.getSession("loginObj") : new LoginObj();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void prepare() throws Exception {
		String existKey = this.getClass().getName() + "_ExistActionForm";
		T form = (T)EhcacheUtil.getInstance().get("queryListCache", existKey);
		if (form == null) {
			/*
			 * 若action extends BaseAction，則不執行底下程序
			 * 若action extends BaseAction<BaseActionForm>，則執行底下程序
			 */
//			System.out.println("String.valueOf(getClass().getGenericSuperclass() = " + String.valueOf(getClass().getGenericSuperclass()));
			if(!"class com.ch.base.element.BaseAction".equals(String.valueOf(getClass().getGenericSuperclass()))){
				ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
				Class<T> viewFormClz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
				form = viewFormClz.newInstance();
				EhcacheUtil.getInstance().put("queryListCache", existKey, form);
			}
		}
		this.actionForm = form;
		
	}
	
	@SuppressWarnings("unchecked")
	protected void clearFormData() {
		String existKey = this.getClass().getName() + "_ExistActionForm";		
		ParameterizedType aParameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
		Class<T> viewFormClz = (Class<T>) aParameterizedType.getActualTypeArguments()[0];
		try {
			actionForm = viewFormClz.newInstance();
			EhcacheUtil.getInstance().put("queryListCache", existKey, actionForm);
		} catch (Exception e) {}
	}
	
	protected Object getSession(String sessionId) {
		Object resultObj = OtherUtils.getSession(sessionId);
		return resultObj;
	}

	protected List goToNextPage(List targetList, int targetPageSize, int targetPageNo){
		displayList = new ArrayList();
		if(targetList != null && targetList.size() > 0){
//			System.out.println("targetList.size() = " + targetList.size());
//			System.out.println("targetPageSize = " + targetPageSize);
//			System.out.println("targetPageNo = " + targetPageNo);
			
			int targetFromIndex;
			int targetToIndex;

			totalPage = targetList.size() / pageSize;
			if ((targetList.size() % pageSize) > 0) {
				totalPage = totalPage + 1;
			}

			targetFromIndex = targetPageSize * (targetPageNo - 1);
			targetToIndex = targetFromIndex + targetPageSize;
			
			if (targetToIndex > targetList.size()) {
				targetToIndex = targetList.size();
			}

			displayList = targetList.subList(targetFromIndex, targetToIndex);

			totalSize = targetList.size();
//			prevPage = currentPage;
			currentPage = targetPageNo;			//顯示列數會用到
			
//			if(totalPage <= targetPageNo + 1){
//				nextPage = targetPageNo + 1;
//			}else{
//				nextPage = currentPage;
//			}
			
//			System.out.println("totalSize = " + totalSize);
//			System.out.println("currentPage = " + currentPage);
//			System.out.println("pageSize = " + pageSize);
//			System.out.println("totalPage = " + totalPage);
		}
		return displayList;
	}
	
	protected void returnAJAXResult(Map<String, ?> returnMap) throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");
		response.setHeader("Cache-Control", "no-cache");        
	    response.setCharacterEncoding("UTF-8");	//避免中文回傳亂碼問題

	    PrintWriter out;
		out = response.getWriter();
		JSONObject json = new JSONObject();
		
		for (Map.Entry<String, ?> entry : returnMap.entrySet()){
			json.accumulate(entry.getKey(), entry.getValue());
		}
		
		out.println(json);
		out.flush();
		out.close();
	}

	public Map getSession() {
		return session;
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public T getActionForm() {
		return actionForm;
	}

	public void setActionForm(T actionForm) {
		this.actionForm = actionForm;
	}

	public LoginObj getLoginObj() {
		return loginObj;
	}

	public void setLoginObj(LoginObj loginObj) {
		this.loginObj = loginObj;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public String getErrorSolution() {
		return errorSolution;
	}

	public void setErrorSolution(String errorSolution) {
		this.errorSolution = errorSolution;
	}

	public List getDisplayList() {
		return displayList;
	}

	public void setDisplayList(List displayList) {
		this.displayList = displayList;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getTotalSize() {
		return totalSize;
	}

	public void setTotalSize(int totalSize) {
		this.totalSize = totalSize;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

//	public int getPrevPage() {
//		return prevPage;
//	}
//
//	public void setPrevPage(int prevPage) {
//		this.prevPage = prevPage;
//	}

	public int getNextPage() {
		return nextPage;
	}

	public void setNextPage(int nextPage) {
		this.nextPage = nextPage;
	}

}
